package com.cheksin.excl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.cheksin.entity.Goods;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

 /**
  * 格式化导出excl
  * @author 大魔王
  *
  */
public class ExportXlsx {
	private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    public static void main(String[] args) throws Exception{
        String[] header = {"名称（必填）", "分类（必填）", "条码", "主编码", "规格", "主单位", "库存量", "进货价（必填）", "销售价（必填）", "毛利率", "批发价", "会员价", "会员折扣", "积分商品",
                "库存上限", "库存下限", "库位", "品牌", "供货商", "生产日期", "保质期", "拼音码", "货号", "市场价", "过期日", "自定义3", "重量", "称编码", "商品状态", "商品描述", "创建日期"};
        //exportExcl(header,genGoods(new File("d:\\商品资料.xlsx")),"d:\\商品资料-back.xls");

    }
    /**
     *银豹文件生成
     * @author 不愿透露
     * @date 2021/11/19 11:35
     * @param file
     * @return java.util.List<com.cheksin.excl.Goods>
     */
    public static List<?> genGoods(File file){
        List<Goods> goodsALL = ReadExcelUtil.readExcelInfo(file);
        for (Goods goods : goodsALL) {
            String mc = goods.getMc();
            mc = mc.replaceAll("（","(").replaceAll("）",")");
            goods.setMc(mc);
            String bzc = (goods.getBzq()==null || goods.getBzq()=="") ? "300" : goods.getBzq();
            int negativeVal = (~(Integer.valueOf(bzc) - 1));
            goods.setBzq(bzc);
            String date = goods.getGqr();
            if(date.length()>8) {
                String scrq = "2021-11-01";;
                Date dates = null;
                try {
                    dates = SIMPLE_DATE_FORMAT.parse(date);
                }catch (Exception e) {
                    dates = new Date();
                }
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(dates);
                rightNow.add(Calendar.DATE, negativeVal);
                Date dt1 = rightNow.getTime();
                scrq = SIMPLE_DATE_FORMAT.format(dt1);
                goods.setScrq(scrq);
                goods.setHyzk("是");
                goods.setHyj(goods.getXsj());
                goods.setPfj(goods.getXsj());
                if(goods.getGg() == null || goods.getGg() == "") {
                    goods.setGg("中国");
                }
                if(goods.getZdw().equals("无")) {
                    String name = goods.getMc();
                    String zdw = name.substring(name.lastIndexOf(")")+1,name.length());
                    goods.setZdw(zdw);
                }
            }
        }
        return goodsALL;
     }

    /**
     *通用生成excl
     * @author 不愿透露
     * @date 2021/11/19 11:34
     * @param header 标题头
     * @param data 数据
     * @param exportPath 导出路径
     */
    public static void exportExcl(String[] header, List<?> data, String exportPath,Object goods) {


        File file = new File(exportPath);
        if(file.exists()) {
            System.out.println("文件删除，重新创建！");
            file.delete();
        }
        String[] fieldNames = fieldName(goods.getClass());
        Workbook wb = new HSSFWorkbook();
        int rowSize = 0;
        Sheet sheet = wb.createSheet();
        Row row = sheet.createRow(rowSize); 
        for (int i = 0; i < header.length; i++) {
            row.createCell(i).setCellValue(header[i]);
        }
 
        try {
            for (int x = 0; x < data.size(); x++) {
                rowSize = 1;
                Row rowNew = sheet.createRow(rowSize + x);
                for (int i = 0; i < header.length; i++) {
                    Object user = data.get(x);
                    for (int i1 = 0; i1 < fieldNames.length; i1++) {
                        String methodName = "get" + fieldNames[i].substring(0,1).toUpperCase() + fieldNames[i].substring(1);//获取属性的get方法名
                        Method method = user.getClass().getMethod(methodName);
                        Object invoke = method.invoke(user);//获取属性值
                        invoke = invoke == null ? "" : invoke;
                        rowNew.createCell(i).setCellValue(invoke.toString());
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(exportPath);
            wb.write(outputStream);
        } catch (Exception e) {
 
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (Exception e) {
 
            }
            try{
                if(wb != null){
                    wb.close();
                }
            } catch (Exception e){
                
            }
        }
 
    }
 
    public static String[] fieldName(Class clazz) {
        Field[] declaredFields = clazz.getDeclaredFields();
        String[] fieldNames = new String[declaredFields.length];
        for (int i = 0; i < declaredFields.length; i++) {
            fieldNames[i] = declaredFields[i].getName(); //通过反射获取属性名
        }
        return fieldNames;
    }
}